package dao;

import utlis.dbUtils;

import java.sql.*;

public class BaseDao {
    static String driver;
    static String url ;
    static String user;
    static String pass;
    Connection conn ;
    PreparedStatement ps ;
    ResultSet resultSet;
    static {
        driver = dbUtils.getMyproperties("driver");
        url = dbUtils.getMyproperties("url");
        user = dbUtils.getMyproperties("user");
        pass = dbUtils.getMyproperties("pass");
        try {
            Class.forName(driver);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //获取连接
    public  Connection getConnection(){

        try {
            conn = DriverManager.getConnection(url,user,pass);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            return conn;
        }
    }

    //查
    public ResultSet ExecuteQuery(String sql,Object...o){
        this.getConnection();
        ResultSet resultSet=null;
        try {
            ps = conn.prepareStatement(sql);
            if (o!=null&o.length>0){
                for (int i=0; i<o.length ; i++) {
                    ps.setObject(i+1,o[i]);
                }
            }
            resultSet = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            return resultSet;
        }

    }
    //增删改
    public int ExecuteUpdate(String sql,Object...o){
        this.getConnection();
        int j =-1;
        try {
            ps=conn.prepareStatement(sql);
            if (o!=null&o.length>0){
                for (int i = 0; i <o.length ; i++) {
                    ps.setObject(i+1,o[i]);
                }
            }
            j = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            this.Close();
            return j;
        }
    }



    public void  Close(){

        if (resultSet!=null){

            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
